const req = require('../utils/mp-req/index.js');
// api
const userApi = require('./api/user.js');
const wfyyApi = require('./api/wfyy.js');
const common = require('./api/common.js');
const app = require('../app.js');
const apiUrlTable = {
	local: 'http://127.0.0.1',
	dev: 'http://192.168.1.119',
	pre: '',
	release: '',
};
const baseUrl = apiUrlTable.local;

/** 
 * code换取sessionId,通过wx.login获取code后,向服务端发送请求获取对应sessionId
 * @param {string} code
 */
function code2sessionId(code) {
	console.log("code: " + code);
	return new Promise((res, rej) => {
		wx.request({
			url: `${baseUrl}/www/app/xcxlogin.do`,
			method: 'POST',
			timeout: 6000,
			header: {
				type: 1, //表示微信端
				'content-type': 'application/x-www-form-urlencoded',
			},
			data: {
				code: code,
				dlFlag: 1, //不校验登录
				bdFlag: 1,
			},
			success(r1) {
				console.log("r1.data.openid: " + r1.data.openid);
				if (r1.data && r1.data.head && (r1.data.head.code == 1 || r1.data.head.code == 3001)) {
					//保存openid
					wx.setStorage({
						key: "openid",
						data: r1.data.openid,
					});
					res(r1);
				} else {
					if (r1.data) {
						wx.hideLoading();
						wx.showModal({
							showCancel: false,
							content: r1.data.head.message,
						});
					} else {
						rej(r1);
					}
				}
			},
			fail: rej,
		});
	});
}

/**
 * 检查session是否有效/未传入clientId或为空(用户未登录)
 * @param {any} res
 */
function isSessionAvailable(res) {

	return res.head.code != 3000;
}

/**
 * 截器使拦截返回false
 * @param {Object} res
 */
function resInterceptor(res) { 
	console.log(res);
	if (res.head.code == 3001) {
		wx.hideLoading();
		wx.showModal({
			title: '提示',
			content: '当前用户未绑定手机号码,是否前往?',
			cancelColor: '#ff7373',
			confirmText: '前往绑定',
			confirmColor: '#00cb00',
			success(res) {
				if (res.confirm) {
					wx.navigateTo({
						url: '../../pages/registered/registered'
					});
				} else if (res.cancel) {
					/* wx.switchTab({
						url: '../../pages/my/my'
					}) */
				}
			}
		})
		return false;
	}
	if(res.head.code == 405){
		wx.hideLoading();
		req.err.show("服务器异常,请稍后再试~");
		return false;
	}

	return true;
}

req.init({
	baseUrl,
	code2sessionId,
	isSessionAvailable,
	resInterceptor,
});

req.use(userApi);
req.use(wfyyApi);
req.use(common);

module.exports = req;
